<template>
	<cl-crud ref="crud" @load="onLoad" :on-refresh="onRefresh">
		<cl-pagefull @resize="onResize">
			<template #head>
				<el-row type="flex">
					<!-- <cl-flex1> -->
					<cl-filter-group v-model="search" @reset="changeBiz">
						<cl-filter label="所属事业部">
							<cl-select v-model="search.biz_id" placeholder="请选择" filterable @change="changeBiz">
								<el-option v-for="item in business" :key="item.biz_id" :label="item.biz_name"
									:value="item.biz_id" />
							</cl-select>
						</cl-filter>
						<cl-filter label="分公司">
							<cl-select v-model="search.company_id" placeholder="请选择" clearable filterable>
								<el-option label="全部" value="" />
								<el-option v-for="item in bizRefData.company" :key="item.company_id"
									:label="item.company_name" :value="item.company_id" />
							</cl-select>
						</cl-filter>
						<cl-filter label="品牌">
							<cl-select v-model="search.bra_id" placeholder="全部" clearable filterable multiple collapse-tags>
								<el-option v-for="item in bizRefData.brand" :key="item.bra_id" :label="item.bra_name"
									:value="item.bra_id" />
							</cl-select>
						</cl-filter>
						<cl-filter label="所属城市">
							<cl-select v-model="search.city_id" placeholder="请选择" filterable clearable>
								<el-option label="全部" value="" />
								<el-option v-for="item in bizRefData.city" :key="item.id" :label="item.name"
									:value="item.id" />
							</cl-select>
						</cl-filter>
						<cl-filter label="所属门店">
							<cl-shop-select v-model="search.dept_id" placeholder="请选择" filterable clearable multiple
								collapse-tags :biz_id="search.biz_id" />
						</cl-filter>
						<cl-filter label="订单ID">
							<el-input v-model="search.order_no" placeholder="订单ID" clearable style="width: 200px" />
						</cl-filter>
						<cl-filter label="客户关键字">
							<el-input v-model="search.search_content" placeholder="手机号/微信号/客户名称/会员号" clearable
								style="width: 220px" />
						</cl-filter>
						<cl-filter label="订单状态">
							<cl-select v-model="search.pay_status" style="width: 70px" placeholder="请选择" filterable>
								<el-option v-for="item in statusData" :key="item.value" :label="item.label"
									:value="item.value" />
							</cl-select>
						</cl-filter>
						<cl-filter label="是否分期">
							<cl-select v-model="search.is_rest" style="width: 70px" placeholder="请选择" filterable>
								<el-option v-for="item in restStatusList" :key="item.value" :label="item.label"
									:value="item.value" />
							</cl-select>
						</cl-filter>
						<cl-filter label="订单类型">
							<cl-select v-model="search.cus_type" style="width: 70px" placeholder="请选择" filterable clearable>
								<!-- <el-option
									v-for="item in clueCusTypeList"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								/> -->
								<el-option value="" label="全部" />
								<el-option :value="1" label="新客" />
								<el-option :value="2" label="老客" />
								<el-option :value="3" label="老转新" />
							</cl-select>
						</cl-filter>
						<cl-filter label="支付时间">
							<cl-date-picker v-model="search.onsumption" type="daterange" range-separator="至"
								start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd"
								style="width: 210px" :clearable="false" />
						</cl-filter>
						<cl-filter label="排店部门">
							<cl-cascader clearable v-model="search.after_dept_id" :options="afterDeptList" :props="{
								value: 'dept_id',
								label: 'dept_name'
							}" filterable style="width: 100%" @change="changeDept" />
						</cl-filter>
						<cl-filter label="排店人员">
							<cl-select v-model="search.order_date_id_user" placeholder="请选择" clearable style="width: 100%">
								<el-option v-for="item in afterUserList" :key="item.user_id" :label="item.user_name"
									:value="item.user_id" />
							</cl-select>
						</cl-filter>
						<cl-filter label="消费金额">
							<cl-select v-model="search.pay_power" placeholder="请选择" clearable style="width: 100%">
								<el-option v-for="item in payPowerList" :key="item.value" :label="item.label"
									:value="item.value" />
							</cl-select>
						</cl-filter>
					</cl-filter-group>
					<!-- </cl-flex1>
					<div>
						<el-button @click="exportExcel">
							<icon-svg name="icon-download-3" />
						</el-button>
					</div> -->
				</el-row>
			</template>
			<el-row>
				<!-- 数据表格 -->
				<cl-table v-bind="table" id="appointTable" ref="table">
					<cl-empty slot="empty" />
					<template #column-customer="{ scope: { row } }">
						<cl-customer-new :gender="row.cus_sex" :name="row.cus_name" :mobile="row.cus_mobile"
							:wechat="row.cus_wx || '-'" :avatar="row.cus_img" />

					</template>
					<template #column-cus_type="{ scope: { row } }">
						<div class="cus_type" :class="{
							'color-primary': row.cus_type == 1,
							old: row.cus_type == 2,
							'color-danger': row.cus_type == 3,
							'color-warning': row.cus_type == 4
						}">
							{{ row.cus_type | constFilter("CUS_TYPE") }}
						</div>
					</template>
					<template #column-rest_amount="{ scope: { row } }">
						<span :class="{ 'color-danger': !!(row.rest_amount * 1) }">
							{{ row.rest_amount }}
						</span>
					</template>
				</cl-table>
			</el-row>

			<template #foot>
				<el-row type="flex">
					<cl-flex1 />
					<!-- 分页控件 -->
					<zm-pagination />
				</el-row>
			</template>
		</cl-pagefull>
	</cl-crud>
</template>

<script>
import { mapState } from "vuex";
import dayjs from "dayjs";
import { exportExcelCoustom } from "@/utils/excel";
import { delEmptyChildren } from "@/utils";
import { cloneDeep } from "cl-admin/utils";
import { constFilter as constFilterFn } from "@/filters";
import pageMinix from "@/mixins/page"
export default {
	name: "CusShopOrder",
	inject: ["$layout"],
	mixins: [pageMinix],
	data() {
		return {
			// 表格配置
			table: {
				"context-menu": ["refresh"],
				columns: [
					{
						label: "客户信息",
						prop: "customer",
						minWidth: 120,
						align: "left",
						showOverflowTooltip: true,
						fixed: true
					},
					{
						label: "客户昵称",
						prop: "cus_name",
						minWidth: 120,
						align: "left",
						showOverflowTooltip: true,
						fixed: true
					},
					{ label: "订单类型", prop: "cus_type", width: 100 },
					{
						label: "消费信息",
						prop: "items",
						minWidth: 300,
						align: "left",
						showOverflowTooltip: true,
						formatter: row => (row.items || []).map(v => v.prod_name).join(";")
					},
					{ label: "消费金额（￥）", prop: "total_amount", width: 120 },
					{
						label: "分期",
						prop: "is_rest",
						width: 60,
						formatter: row => (row.is_rest == 0 ? "否" : "是")
					},
					{ label: "实际付款（￥）", prop: "pay_amount", width: 120 },
					{ label: "合作款（￥）", prop: "costmoney", width: 120 },
					{ label: "欠款金额（￥）", prop: "rest_amount", width: 120 },
					{ label: "订单ID", prop: "order_no", width: 170 },
					{
						label: "备注",
						prop: "remarks",
						minWidth: 150,
						align: "left",
						showOverflowTooltip: true
					},
					{ label: "创建时间", prop: "add_time", width: 140 },
					{ label: "支付时间", prop: "pay_time", width: 140 },

					{
						label: "订单状态",
						prop: "status",
						width: 120,
						formatter: row => {
							if (row.is_rest == 1 && row.finish_rest == 0) {
								return "分期中";
							}
							if (row.is_rest == 1 && row.finish_rest == 1) {
								return "已还清";
							}
							return this.$constFilter(row.status, "ORDER_STATUS");
						}
					},
					{
						label: "所属门店",
						prop: "dept_name",
						minWidth: 150,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "所属事业部",
						prop: "biz_name",
						minWidth: 150,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "分公司",
						prop: "company_name",
						minWidth: 150,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "品牌",
						prop: "bra_name",
						minWidth: 150,
						align: "left",
						showOverflowTooltip: true
					},
					{ label: "支付方式", prop: "pay_type", width: 120 }
				],
				props: {
					maxHeight: 500,
					fit: false
				},
				on: {
					"row-click": row => {
						this.$layout.openCusDetail(row, "order");
					}
				}
			},
			companyList: [],
			brandList: [],
			shopList: [],
			cityList: [],
			statusData: [
				{ value: 0, label: "全部" },
				{ value: 1, label: "待付款" },
				{ value: 3, label: "分期中" },
				{ value: 5, label: "付款中" },
				{ value: 11, label: "退款中" },
				{ value: 6, label: "已退款" },
				{ value: 4, label: "已付款" },
				{ value: 2, label: "已取消" },
				{ value: 12, label: "已还清" }
			],
			restStatusList: [
				{ value: 0, label: "全部" },
				{ value: 1, label: "是" },
				{ value: 2, label: "否" }
			],
			clueCusTypeList: [
				{ value: "", label: "全部" },
				{ value: 0, label: "普通订单" },
				{ value: 1, label: "派单订单" }
			],
			search: {
				search_content: "",
				biz_id: "",
				company_id: "",
				bra_id: [],
				city_id: "",
				after_dept_id: [],
				order_date_id_user: "",
				dept_id: [], //门店
				order_no: "",
				pay_status: 0,
				is_rest: 0,
				clue_cus_id: "",
				cus_type: "",
				search_type: 6,
				onsumption: [
					dayjs(new Date()).format("YYYY-MM-DD"),
					dayjs(new Date()).format("YYYY-MM-DD")
				],
				btime: "",
				etime: "",
				pay_power: ''
			},
			afterDeptList: [],
			afterUserList: [],
			payPowerList: [
				{
					label: '1000以下',
					value: 1
				},
				{
					label: '1000 ~ 3000',
					value: 2
				},
				{
					label: '3000 ~ 5000',
					value: 3
				},
				{
					label: '5000 ~ 10000',
					value: 4
				},
				{
					label: '10000以上',
					value: 5
				}
			]
		};
	},
	computed: {
		...mapState("common", ["visibleCusDetail", "cusFormSubmit"]),
		bizRefData() {
			const { biz_id } = this.search;
			return this.getBizRefData(biz_id);
		}
	},
	watch: {
		visibleCusDetail(v) {
			if (!v && this.zmComponentIsActive) {
				this.refresh(false);
			}
		},
		cusFormSubmit(v) {
			if (v && this.zmComponentIsActive) {
				this.refresh();
			}
		}
	},
	async created() {
		this.search.biz_id = this.getCurrBiz();
		this.init();
	},
	methods: {
		async init() {
			const { biz_id } = this.search;
			this.getAfterDept();
			this.updateBizRefData(biz_id);
		},
		async onRefresh(params, { next, render, done }) {
			if (!params.bra_id.length) {
				this.$message.warning("请选择品牌");
				return done();
			}
			if (params.search_content && params.search_content.length < 2) {
				this.$message.error("使用关键字搜索时中文至少2位查询，其他至少4位可查询");
				return done();
			}

			// this.loading = true;
			const { data } = await next(params)
			// console.log(data)
			// render(data);
		},
		onLoad({ ctx, app }) {
			ctx.service(this.$service.order).done();
			app.refresh(this.search);
		},
		onResize(h) {
			this.table.props.maxHeight = h;
		},
		// crud刷新
		refresh(reset = true) {
			let params = { ...this.search };
			if (reset) {
				params.page = 1;
			}
			this.$refs.crud.refresh(params);
			this.$nextTick(() => {
				this.$refs.table?.calcMaxHeight?.();
			});
		},
		changeBiz(v) {
			this.search = {
				...this.search,
				company_id: "",
				bra_id: [],
				dept_id: [],
				city_id: "",
				after_dept_id: [],
				order_date_id_user: ""
			};
			this.init();
			// this.refresh();
		},
		changeDept() {
			this.search.order_date_id_user = "";
			this.getManageDeptUser();
		},
		async getAfterDept() {
			const { biz_id } = this.search;
			this.afterDeptList = delEmptyChildren(
				(await this.$store.dispatch("common/getDept", {
					biz_id,
					post: 2,
					needAll: false,
					needCascader: true
				})) || []
			);
			console.log("this.afterDeptList", this.afterDeptList);
		},
		// 获取排店人员
		async getManageDeptUser() {
			const { after_dept_id, biz_id } = this.search;
			// if (Array.isArray(dept_id)) {
			// 	dept_id = dept_id.join();
			// }
			this.afterUserList = [];
			const data = await this.$service.user.deptuserlists({
				biz_id,
				dept_id: after_dept_id[1],
				post: 2
			});
			this.afterUserList = data;
		},
		async exportExcel() {
			const loading = this.$loading({
				lock: true,
				text: "正在导出~"
			});
			const query = {
				...this.search,
				all_page: 1
			};
			const { list } = await this.$service.order.page(query).catch(e => {
				loading.close();
				throw e;
			});

			if (list?.length > 0) {
				const newList = list.map(row => {
					let status = "";
					if (row.is_rest == 1 && row.finish_rest == 0) {
						status = "分期中";
					} else if (row.is_rest == 1 && row.finish_rest == 1) {
						status = "已还清";
					} else {
						status = this.$constFilter(row.status, "ORDER_STATUS");
					}

					const getReceivedProportion = () => {
						const { clue_cus_id, received_proportion } = row;
						if (clue_cus_id == 0) return "-";
						return `${received_proportion}%`;
					};

					const getProfit = () => {
						const { clue_cus_id, profit } = row;
						if (clue_cus_id == 0) return "-";
						return `${profit}`;
					};

					return {
						...row,
						customer: `名字：${row.cus_name};手机号：${row.cus_mobile};微信号：${row.cus_wx}`,
						items: (row.items || []).map(v => v.prod_name).join(";"),
						is_rest: row.is_rest == 0 ? "否" : "是",
						cus_type: constFilterFn(row.cus_type, "CUS_TYPE"),
						status,
						received_proportion: getReceivedProportion(),
						profit: getProfit()
					};
				});
				let columns = cloneDeep([...this.table.columns]);
				columns.pop();
				exportExcelCoustom("订单" + dayjs().format("YYYYMMDDhhmmss"), newList, columns);
			}
			loading.close();
		}
	}
};
</script>

<style lang="scss" scoped></style>
